
module ctpl.plugin ;

import ctpl.all , std.c.string ;

package __gshared extern(C) int function(const(char)*,...) dmd_printf ;

version (Windows) {
	
	import std.c.windows.windows;
	import core.dll_helper;

	static __gshared HINSTANCE g_hInst;

	extern (Windows) BOOL DllMain(HINSTANCE hInstance, ULONG ulReason, LPVOID pvReserved) {
	    switch (ulReason){
		case DLL_PROCESS_ATTACH:
		    g_hInst = hInstance;
		    dll_process_attach( hInstance, true );
		    break;

		case DLL_PROCESS_DETACH:
		    dll_process_detach( hInstance, true );
		    break;

		case DLL_THREAD_ATTACH:
		    dll_thread_attach( true, true );
		    break;

		case DLL_THREAD_DETACH:
		    dll_thread_detach( true, true );
		    break;
	    }
	    return true;
	}
}

export extern(C) size_t plugin_lib_export(size_t ty, void* data) {
	switch(ty){
		case 0:
			dmd_printf	= cast(typeof(dmd_printf)) data ;
			break;
		case 1:
			//dmd_printf("stderr1 = `%x`\n", data);
			break;
		case 2:
			dmd_printf("import path = `%s`\n", cast(char*) data);
			break;
		default:
			dmd_printf("xxx = %d, `%x`\n", ty, data);
			;
	}
	return 0 ;
}

export extern(C) size_t plugin_lib_import(char* in_name, char** out_name, void** out_buffer) {
	
	// *out_buffer	= in_name ; return strlen(in_name) ;

	char* _in_name = in_name ;
	int 	i = 0 ;
	while( _in_name[i] !is 0 ) i++;
	auto args	=  cast(char[]) in_name[0..i] ;
	
	auto ret	= CTpl.ImportInvoke( args );
	
	if(  ret is null || ret.length is 0 ) {
		return 0 ;	
	}
	
	*out_buffer	= cast(void*) toStringz(ret) ;
	
	return ret.length ;
}

